package com.dg11185.nearshop.activity.user.info;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.utils.netstate.NetWorkUtils;
import com.dg11185.libs.utils.screen.ScreenSize;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.user.ModifyPasswdActivity;
import com.dg11185.nearshop.activity.user.order.AddressActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.MyApplication;
import com.dg11185.nearshop.net.response.GetUserDetailResponse;
import com.dg11185.nearshop.net.response.LoginResponse;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

/**
 * 
 * @author：Daibo    
 * @time：2014-9-12 上午10:48:24
 */
public class UserInfoActivity extends SubPageActivity implements OnClickListener, IUserInfoView {

    // 返回到UserFragment时的一些状态码，用于UserFragment识别一些状态来进行UI更新
    public final static int LOGOUT = 100;// 注销登录
    public final static int MODIFY_PWD_ACTY = 21;

    private String mLoginName;
    public LoginResponse user = null;
    private LoadLayoutWithTweenAnim loadView = null;
    private ScrollView dataView = null;
    private Dialog submitDialog = null;
    private TextView tvBrithday, tvGender;
    private GetUserDetailResponse userDetail = null;
    
    private UserInfoPresenter presenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info);
        setSubPageTitle("个人资料");
        user = MyApplication.getUser();
        mLoginName = getIntent().getStringExtra(Constants.LOGIN_NAME);

        loadView = (LoadLayoutWithTweenAnim) this.findViewById(R.id.user_info_loading);
        loadView.setStateHandler(stateListener);
        submitDialog = com.dg11185.nearshop.app.ViewUtils.createSubmittingDialog(this);
        dataView = (ScrollView) this.findViewById(R.id.user_info_data);
        this.findViewById(R.id.user_info_brithday).setOnClickListener(this);
        this.findViewById(R.id.user_info_modify_pwd).setOnClickListener(this);
        this.findViewById(R.id.user_info_gender).setOnClickListener(this);
        this.findViewById(R.id.user_info_logout).setOnClickListener(this);
        this.findViewById(R.id.user_info_modify_address).setOnClickListener(this);

        TextView nameTxt = (TextView) this.findViewById(R.id.user_info_name_txt);
        TextView phoneTxt = (TextView) this.findViewById(R.id.user_info_phone_txt);
        TextView emailTxt = (TextView) this.findViewById(R.id.user_info_mail_txt);
        tvBrithday = (TextView) this.findViewById(R.id.user_info_brithday_txt);
        tvGender = (TextView) this.findViewById(R.id.user_info_gender_txt);
        nameTxt.setText(user.userName);
        phoneTxt.setText(user.mobilePhone);
        emailTxt.setText(user.email);
        presenter = new UserInfoPresenter(this, user.userId);
        presenter.getUserInfo();
    }

    @Override
    protected void onDestroy() {
        NetClient.httpCancel(this, true);
        super.onDestroy();
    }

    @Override
    public void showLoadingView() {
        loadView.onLoading();
        dataView.setVisibility(View.GONE);
    }

    @Override
    public void showUserInfo(GetUserDetailResponse result) {
        userDetail = result;
        loadView.onLoadSuccess();
        dataView.setVisibility(View.VISIBLE);
        tvBrithday.setText(result.birthday);
        if ("0".equals(result.sex)) {
            tvGender.setText("男");
        } else {
            tvGender.setText("女");
        }
    }

    @Override
    public void onLoadingFailure(int resultCode) {
        if (resultCode == NetClient.NET_DISCONNECT_CODE) {
            ViewUtils.showToast(this, R.string.cant_connect_network);
        }
        loadView.setLoadFailedHint("服务器连接失败! ");
        loadView.onLoadFailed();
    }

    @Override
    public void showSubmitDialog() {
        submitDialog.show();
    }

    @Override
    public void onSubmitSuccess(){
        submitDialog.dismiss();
        ViewUtils.showToast(this, "修改成功");
    };

    @Override
    public void onSubmitFailure(int resultCode){
        if (resultCode == NetClient.NET_DISCONNECT_CODE) {
            ViewUtils.showToast(this, R.string.cant_connect_network);
        }
        submitDialog.dismiss();
    };
    @Override
    public void onClick(View v) {
        if (!NetWorkUtils.isNetConnected()) {
            ViewUtils.showToast(this, R.string.cant_connect_network);
            return;
        }
        switch (v.getId()) {
        case R.id.user_info_brithday:
            modifyBirthday();
            break;
        case R.id.user_info_gender:
            initGenderView();
            break;
        case R.id.user_info_modify_address:
            startActivity(new Intent(this, AddressActivity.class));
            break;
        case R.id.user_info_modify_pwd:
            Intent modifyPwd = new Intent(this, ModifyPasswdActivity.class);
            modifyPwd.putExtra(Constants.LOGIN_NAME, mLoginName);
            startActivityForResult(modifyPwd, MODIFY_PWD_ACTY);
            break;
        case R.id.user_info_logout:
            MyApplication.setUser(null);
            setResult(LOGOUT);
            // 注销用户，需要清空缓存
            this.finish();
            break;
        default:
            break;
        }
    }

    /**
     * 初始化DatePicker，需要判断值是否越界
     * 
     * @Exception IllegalArgumentException
     */
    private void modifyBirthday() {
        String birthday = "1990-01-01";
        if (userDetail != null) {
            if (userDetail.birthday.length() > 9) {
                birthday = userDetail.birthday;
            }
        }
        int year = Integer.parseInt(birthday.substring(0, 4));
        int month = Integer.parseInt(birthday.substring(5, 7));
        int day = Integer.parseInt(birthday.substring(8, 10));
        if (1900 > year || 2100 < year) {
            year = 1990;
        }
        if (1 > month || 12 < month) {
            month = 1;
        }
        if (1 > day || 31 < day) {
            day = 1;
        }
        DatePickerDialog dialog = new DatePickerDialog(this, datelistener,
                year, month - 1, day);
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
        // 从修改密码的界面中返回
        case MODIFY_PWD_ACTY:
            // 如果密码修改成功，注销用户，回到个人中心，让用户使用新密码重新登录
            if (resultCode == RESULT_OK) {
                setResult(LOGOUT);
                finish();
            }
            break;
        default:
            break;
        }
    }

    /**
     * 
     */
    private DatePickerDialog.OnDateSetListener datelistener = new DatePickerDialog.OnDateSetListener() {
        /**
         * params：view：该事件关联的组件 params：myyear：当前选择的年 params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear,
                int dayOfMonth) {
            monthOfYear++;
            String month = "";
            String day = "";
            if (monthOfYear < 10) {
                month = "0" + monthOfYear;
            } else {
                month = monthOfYear + "";
            }
            if (dayOfMonth < 10) {
                day = "0" + dayOfMonth;
            } else {
                day = dayOfMonth + "";
            }
            String brithday = myyear + "-" + month + "-" + day;
            if (!brithday.equals(userDetail.birthday)) {
                tvBrithday.setText(brithday);
                presenter.modifyBirthday(brithday);
            }
        }
    };

    private void initGenderView() {
        final Dialog dialog = new Dialog(this, R.style.wl_CustomDialog);
        dialog.setContentView(R.layout.common_gender_choice);
        TextView male = (TextView) dialog.findViewById(R.id.gender_male);
        TextView female = (TextView) dialog.findViewById(R.id.gender_female);

        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        int width = ScreenSize.getInstance().screenPxWidth;
        float density = ScreenSize.getInstance().density;

        if (width / density > 600) {
            lp.width = (int) (width * 0.7 * 0.7);
        } else {
            lp.width = (int) (width * 0.6);
        }

        dialog.getWindow().setAttributes(lp);

        dialog.show();
        male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (!"0".equals(userDetail.sex)) {
                    tvGender.setText("男");
                    userDetail.sex = "0";
                    presenter.modifyGender("0");
                }
            }
        });

        female.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (!"1".equals(userDetail.sex)) {
                    tvGender.setText("女");
                    userDetail.sex = "1";
                    presenter.modifyGender("1");
                }
            }
        });
    }
    private LoadStateHandler stateListener = new LoadStateHandler() {

        @Override
        public void onReload() {
            presenter.getUserInfo();
        }

        @Override
        public void onLoading() {

        }

        @Override
        public void onLoadSuccess() {

        }

        @Override
        public void onLoadFailed() {
        }
    };

}
